#!/usr/bin/env python -u
# -*- coding: utf-8 -*-

import sys
import conf
import re
import time
from syslog import *
from utils import message_dialog,threaded
from uimanager import UIManager
from htmlpanel import HTMLPanel
from aboutwindow import AboutWindow
from preferenceswindow import PreferencesWindow
from messagewindow import MessageWindow
from exception import TryOutException, ConnectException,LoginException
from systemicon import SystemIcon
from twittermanager import TwitterManager

try:
    import pygtk
    pygtk.require("2.0")
    import gtk
    import gtk.glade    
except ImportError,cause:
    sys.stderr.write("ImportError: Module is not present %s" % cause)
    sys.exit(1)
    
class MainWindow():
    def __init__(self):
        # main window configuration
        self.uimanager = UIManager("main_window")
        self.window = self.uimanager.widget("main_window")
        
        # instantiate the HTMLPanel 
        self.html_panel = HTMLPanel()

        # add browser doc widget
        self.uimanager.widget("browser_doc").add(self.html_panel.widget())

        # set status bar
        self.status_bar = self.uimanager.widget("status_bar")

        # set window title, size and gravity
        self.window.set_title("%s %s" % (conf.PROGRAM_NAME,conf.PROGRAM_VERSION))
        self.window.set_default_size(200,400)
        self.window.set_gravity(gtk.gdk.GRAVITY_NORTH_EAST)

        # system tray icon
        self.systemicon = SystemIcon(self)
        
        # set twitter manager 
        self.twitter_manager = TwitterManager()

        # Config twitter api and confs
        self._refresh()

        # get the last window pos
        self.window.move(
            int(conf.get_config().get("window_pos","x")),
            int(conf.get_config().get("window_pos","y")))

        # Start conf the signals
        try:
            
            # when click in X call this
            sys_dic = {"on_main_window_delete_event" : self.show_hide_window}
            self.uimanager.add_signal(sys_dic)

            # twitter functions
            twitter_dic = {
                "on_menu_new_message_activated" : self.new_message,
                "on_menu_exit_activated" : self.exit_app,
                "on_menu_refresh_activated" : self.refresh}
            self.uimanager.add_signal(twitter_dic)

            # preferences window functions
            edit_dic = {"open_preferences_window" : self.open_preferences_window}
            self.uimanager.add_signal(edit_dic)
           
            # callback fod about dialog
            help_dic = {"open_about_screen" : self.open_about_window}
            self.uimanager.add_signal(help_dic)

            # update positions
            up_pos = {"on_main_window_set_focus" : self.on_main_window_set_focus}
            self.uimanager.add_signal(up_pos)

            # Connecting the signals with ui interface
            self.uimanager.signals_connect()

        except TypeError,cause:
            sys.stderr.write(str("TypeError: %s\n" % cause))
            exit(-1)
        except AttributeError,cause:
            sys.stderr.write(str("AttributeError: %s\n" % cause))
            exit(-1)
            
    # Show our window
    def show(self):
        self.window.show_all()

    def hide(self):
        self.window.hide()

    # New message window
    def new_message(self,widget,data = None):
        message_window = MessageWindow()
        resp = message_window.run()
        msg = message_window.get_text()
        if(resp):
            self._new_message(msg)

    @threaded
    def _new_message(self,msg):
        self.status_bar.push(0,"Enviando mensagem")
        try:
            self.twitter_manager.send_message(msg)
        except TryOutException,cause:
            self.status_bar.push(0,str(cause))
            return
        self.status_bar.push(0,"Mensagem enviada")        

    # New direct message
    def new_direct_message(self,widget,data = None):
        print "new direct message"

    # Open a preferences window
    def open_preferences_window(self,widget,data = None):
        PreferencesWindow().run()
        self._refresh()

    # Open about window
    def open_about_window(self,*args):
        AboutWindow(self.window).show_about_window()
    
    def refresh(self,widget,data = None):
        self._refresh()

    @threaded
    def _refresh(self):
        self.status_bar.push(0,"Atualizando ...")

        try:
            tl = self.twitter_manager.get_timeline()
        except TryOutException,cause:
            self.status_bar.push(0,str(cause))
            return
            
        gtk.gdk.threads_enter() 
        self.html_panel.push_list(tl)
        gtk.gdk.threads_leave()
        
        self.html_panel.write()                
        self.status_bar.push(0,"Atualizado")
  
    # exit application
    def exit_app(self,*args):
        gtk.main_quit()
        exit(0)

    def show_hide_window(self,*args):
        if self.window.get_property("visible") == True:
            self.window.hide()
        else:
            self.window.show()
        return True
    
    def on_main_window_set_focus(self,*args):
        x,y = self.window.get_position()
        if x and y:
            c = conf.get_config()
            c.set("window_pos","x",x)
            c.set("window_pos","y",y)
            conf.set_config(c)
